<template>
  <div class="zh-asset-import">
    <nav-header>
      <template slot="menuBefore">
        <li>
          <router-link to="/affairs/period/class_timetable" tag="a"
            >课程表</router-link
          >
        </li>
        <li class="gap">&gt;</li>
      </template>
    </nav-header>

    <div class="zh-import-comter">
      <el-button plain class="downLoadtemplate" @click="downloadDemo"
        >下载模板</el-button
      >
    </div>

    <div>
      <header class="upload_search">
        <div class="search_box">
          <span>学年学期：</span>
          <el-select
            v-model="searchParams.termValue"
            @change="handleChange('term')"
          >
            <el-option
              v-for="item in termOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <div class="search_box">
          <span>教学周：</span>
          <el-select
            v-model="searchParams.weeksValue"
            @change="handleChange('week')"
          >
            <el-option
              v-for="item in weeksOptions"
              :key="item.label"
              :label="item.label"
              :value="item.value"
          /></el-select>
        </div>

        <div class="search_box">
          <span>班级：</span>
          <el-select v-model="searchParams.classValue">
            <el-option
              v-for="item in classOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </header>

      <uploader
        :options="uploadOptions"
        :autoStart="false"
        ref="uploader"
        :file-status-text="statusText"
        @files-submitted="fileSubmit"
        @file-removed="fileRemoved"
        @file-success="fileSuccess"
        @file-error="fileFail"
        class="uploader-example"
      >
        <uploader-unsupport></uploader-unsupport>
        <uploader-btn
          :directory="false"
          :attrs="attrs"
          v-if="selectFileShow"
          :single="true"
          class="select_file"
        >
          上传文件
        </uploader-btn>
        <uploader-list v-if="!selectFileShow"></uploader-list>
      </uploader>
      <el-button
        type="primary"
        v-if="!selectFileShow"
        @click="fileUpload"
        style="margin-top: 10px;"
        >确定导入</el-button
      >

      <hr />

      <div class="import_container">
        <el-table
          :show-header="false"
          :data="historyImport"
          style="width: 100%"
          height="200"
        >
          <el-table-column prop="name"> </el-table-column>
          <el-table-column prop="size"> </el-table-column>
          <el-table-column prop="status">
            <template slot-scope="scope">
              <div class="import_ul">
                <span
                  :class="{
                    normal: true,
                    error: scope.row.status === 3,
                    success: scope.row.status === 1
                  }"
                >
                  {{ enumStatus[scope.row.status] }}
                </span>
                <span
                  v-if="scope.row.status === 3"
                  class="error_info"
                  @click="handleViewErrorInfo(scope.row)"
                  >查看</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="address">
            <template slot-scope="scope">
              <div>
                <img
                  style="cursor: pointer;"
                  @click="handleDel(scope.row)"
                  src="../../../../static/image/affairs/ai/del_class.png"
                  alt=""
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="zh-import-text">
      <p>注意事项:</p>
      <p>1、格式支持，Excel2003版本及以上的<span>xls/xlsx</span>格式。</p>
      <p>
        2、Excel表数据从第二行开始有效，<span>科目、授课老师、上课场地为必填项</span>。
      </p>
      <p>
        3、课程信息中，必须包含科目、授课老师、授课场地(校园分区)，请保证系统中已有信息，否则匹配不成功将会导入失败。
      </p>
      <p>
        4、如果该课程需要直录播，则需要填上录播名称。如果不需要直录播，则无需填写。请参考一下示例。
      </p>
      <p>
        5、课表导入的功能是增量导入，导入时如果是已有的课程则不会更改，只是增加新的课程。
      </p>
      <p>6、如果改课程已预约了直录播任务，导入时则不更改原有任务。</p>
    </div>
    <div class="zh-import-table">
      <p>例：</p>
      <div class="zh-table">
        <div class="zh-table-contents">
          <el-table :data="importData" border fixed style="width: 100%">
            <el-table-column
              prop="1"
              label="节次"
              align="center"
              width="150"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <div class="class_section">
                  <span>{{ scope.row[1].name }}</span>
                  <span>{{ scope.row[1].time }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="2"
              label="周一(1.22)"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <div class="class_course">
                  <div class="section_info">
                    <div>
                      <span> {{ scope.row[3].subject_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].teacher_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].class_name }}</span>
                    </div>

                    <div>
                      <span> {{ scope.row[3].live_status_str }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="3"
              label="周二(1.23)"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <div class="class_course">
                  <div class="section_info">
                    <div>
                      <span> {{ scope.row[3].subject_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].teacher_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].class_name }}</span>
                    </div>

                    <div>
                      <span> {{ scope.row[3].live_status_str }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="4"
              label="周三(1.24)"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <div class="class_course">
                  <div class="section_info">
                    <div>
                      <span> {{ scope.row[3].subject_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].teacher_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].class_name }}</span>
                    </div>

                    <div>
                      <span> {{ scope.row[3].live_status_str }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="5"
              label="周四(1.25)"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <div class="class_course">
                  <div class="section_info">
                    <div>
                      <span> {{ scope.row[3].subject_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].teacher_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].class_name }}</span>
                    </div>

                    <div>
                      <span> {{ scope.row[3].live_status_str }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="6"
              label="周五(1.26)"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <div class="class_course">
                  <div class="section_info">
                    <div>
                      <span> {{ scope.row[3].subject_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].teacher_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].class_name }}</span>
                    </div>

                    <div>
                      <span> {{ scope.row[3].live_status_str }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="7"
              label="周六(1.27)"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <div class="class_course">
                  <div class="section_info">
                    <div>
                      <span> {{ scope.row[3].subject_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].teacher_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].class_name }}</span>
                    </div>

                    <div>
                      <span> {{ scope.row[3].live_status_str }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="8"
              label="周日(1.28)"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <div class="class_course">
                  <div class="section_info">
                    <div>
                      <span> {{ scope.row[3].subject_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].teacher_name }}</span>
                    </div>

                    <div>
                      <span>{{ scope.row[3].class_name }}</span>
                    </div>

                    <div>
                      <span> {{ scope.row[3].live_status_str }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <el-dialog title="提示" :visible.sync="viewModal" width="30%">
      <ul class="view_ul">
        <li v-for="(item, index) in viewInfo.error_data" :key="index">
          {{ item }}
        </li>
      </ul>
    </el-dialog>
  </div>
</template>
<script>
import { uploaderFileFail, debounce, longTimeMessage } from "@/tools/tool.js";

let timer = null;
const enumStatus = {
  0: "未导入", // 未执行
  1: "导入成功", // 执行成功
  2: "导入中", // 执行中
  3: "导入失败" // 执行失败
};
export default {
  data() {
    return {
      classOptions: [],
      weeksOptions: [],
      termOptions: [],
      enumStatus,
      searchParams: {
        termValue: "",
        weeksValue: "",
        classValue: ""
      }, // 上传参数
      viewModal: false, // 查看失败弹窗
      viewInfo: {}, // 查看失败详情
      historyImport: [], // 导入历史记录
      messageObj: {},
      statusText: {
        success: "上传成功",
        error: "上传出错",
        uploading: "正在上传...",
        paused: "暂停",
        waiting: "等待上传"
      },
      selectFileOrNot: false, //是否选中文件
      uploadOrNot: false, //是否已经上传
      uploadInfo: {
        file_name: "",
        file_path: "",
        file_size: 0
      },
      attrs: {
        accept: [
          "application/vnd.ms-excel",
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        ]
      },
      uploadOptions: {
        target: this.BASE_URL + "/api/user/vue_userdemo_upload",
        testChunks: false,
        headers: { Authorization: `Bearer ` + this.$g.access_token }
      },
      fileList: [],
      rules: {},
      selectFileShow: true, //是否显示选择文件按钮
      uploadRetryTimes: 100, //文件最大重传次数
      importData: [
        {
          1: {
            name: "语文",
            time: "(9:00 - 9:45)"
          },
          2: {},
          3: {
            live_status_str: "31班录播主机01",
            teacher_name: "何其莘",
            class_name: "体育馆",
            subject_name: "语文"
          },
          4: {},
          6: {},
          7: {},
          8: {}
        }
      ],
      excelUploader: null // 上传组件引用
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.excelUploader = this.$refs.uploader.uploader;
    });
    this.getTermOption();
    this.getClassOption();
    this.getHistoryImportInfo();
  },
  methods: {
    // 获取学期选项
    getTermOption() {
      const success = res => {
        const { data } = res;
        this.termOptions = data.map(item => {
          return {
            value: item.id,
            label: `${item.start_year}-${item.semester_name}`,
            ...item
          };
        });

        // 默认选中第一个
        this.searchParams.termValue = this.termOptions[0].value || "";
        this.getWeeksOption();
      };

      this.$ajax.get("api/term/term_list", { func: { success } });
    },

    // 获取周选项
    getWeeksOption() {
      const success = res => {
        const { data } = res;

        this.weeksOptions = data.map(item => {
          const { week_name, week_num } = item;
          return {
            value: week_num,
            label: week_name,
            ...item
          };
        });

        this.weeksOptions.unshift({
          value: "999",
          label: "全部"
        });

        this.searchParams.weeksValue = this.weeksOptions[0].value || "";
      };
      const params = {
        term_id: this.searchParams.termValue
      };
      this.$ajax.get("api/term/getTermWeekTimeList", {
        params,
        func: { success }
      });
    },

    // 获取班级选项
    getClassOption() {
      const success = res => {
        const { data } = res;

        this.classOptions = data.map(item => {
          return {
            value: item.id,
            label: item.rename
          };
        });

        // 默认选中第一个
        this.searchParams.classValue = this.classOptions[0].value || "";
      };
      const params = {
        status: [1]
      };
      this.$ajax.get("api/org/classes", { params, func: { success } });
    },

    // 获取当前周
    getCurrentWeek() {
      const success = res => {
        const { data, stutas } = res;
        const termData = this.termOptions[0] || {};
        const termEnd = new Date(termData.end_time);
        const nowDate = new Date(this.handleDateFormat());

        if (nowDate < termEnd) {
          // 在当前学期内
          this.searchParams.weeksValue = data.week.week_num || "";
        } else {
          // 不在当前学期内 默认选中第一个
          this.searchParams.weeksValue = this.weeksOptions[0].value || "";
        }
      };

      this.$ajax.get("api/term/getNowTermWeekTime", {
        func: { success }
      });
    },

    // 当前日期时间
    handleDateFormat() {
      const date = new Date();
      // 获取年、月、日
      const year = date.getFullYear();
      let month = date.getMonth() + 1; // 月份是从0开始计数的，所以要加1
      let day = date.getDate();

      // 如果月份或日期是单个数字，则在前面补0
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;

      return year + "-" + month + "-" + day;
    },

    /**
     * 下载导出模板
     */
    downloadDemo() {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        this.handleExport();
      }, 500);
    },

    handleExport() {
      this.export_excel(
        "api/school/syllabusTemplateExport",
        {},
        "课程表模版下载"
      );
    },

    //删除模版历史记录
    handleDel(delItem) {
      const params = {
        id: delItem.id
      };
      const success = res => {
        this.$message.success("删除成功");
        this.getHistoryImportInfo();
      };
      const fail = res => {
        this.$message.error(res.msg);
      };
      this.$ajax.delete("api/school/syllabusImport", {
        params,
        func: { success, fail }
      });
    },

    // 查看失败内容
    handleViewErrorInfo(viewErrorInfo) {
      this.viewModal = true;
      this.viewInfo = viewErrorInfo;
    },

    // 获取历史导入记录
    getHistoryImportInfo() {
      const success = res => {
        const { data } = res;
        this.historyImport = data;
      };
      this.$ajax.get("api/school/syllabusImport", {
        func: { success }
      });
    },

    // 选择器value变化
    handleChange(type) {
      switch (type) {
        case "term":
          if (this.searchParams.termValue) {
            this.getWeeksOption();
          } else {
            this.weeksOptions = [];
            this.searchParams.weeksValue = "";
          }
          break;
        case "weeks":
          break;
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.selectFileOrNot) {
            this.fileUpload();
          } else {
            this.resourceSave();
          }
        } else {
          return false;
        }
      });
    },
    resourceSave() {
      const { file_path, file_name } = this.uploadInfo;
      const { termValue, weeksValue, classValue } = this.searchParams;

      const resourceParam = {
        path: file_path,
        name: file_name,
        term_id: termValue,
        weeks: weeksValue,
        class_id: classValue
      };
      // if (this.uploadOrNot) {
      //   resourceParam.path = this.uploadInfo.file_path;
      // }

      const success = data => {
        this.$message.success("导入成功");
        setTimeout(() => {
          this.$router.go(-1);
        }, 1000);
      };
      const fail = res => {
        longTimeMessage(this, res, 5000);

        setTimeout(() => {
          this.getHistoryImportInfo();
        }, 1000);
      };

      this.$ajax.post("api/school/syllabusImport", resourceParam, {
        func: { success: success, fail: fail }
      });
    },
    //上传成功的事件
    fileSuccess(rootFile, file, message, chunk) {
      this.selectFileShow = true;
      var mess = eval("(" + message + ")");
      mess = handleResponseData(mess);

      if (parseInt(mess.data.status) === 1) {
        this.uploadOrNot = true;
        this.uploadInfo.file_name = mess.data.file_name;
        this.uploadInfo.file_path = mess.data.file_path;
        this.uploadInfo.post_fix = mess.data.post_fix;

        this.resourceSave();
      }
      this.excelUploader.removeFile(file);
    },
    fileFail(rootFile, file, message, chunk) {
      uploaderFileFail(this, this.excelUploader, file, message);
    },
    //过滤文件格式
    fileSubmit(files, fileList, event) {
      for (var i = 0; i < fileList.length; i++) {
        this.uploadInfo.file_size = fileList[i].size;
        this.selectFileOrNot = true;
        this.selectFileShow = false;
      }
    },
    fileRemoved(file) {
      this.selectFileOrNot = false;
      this.selectFileShow = true;
    },
    fileUpload() {
      const { termValue, weeksValue, classValue } = this.searchParams;
      if (!termValue || !weeksValue || !classValue) {
        return this.$message.error("请选择学期、教学周、班级");
      }
      this.excelUploader.upload();
    }
  },
  destroyed(to, from, next) {
    this.$message.closeAll();
  }
};
</script>
<style lang="scss" scoped>
.zh-asset-import {
  .zh-import-comter {
    margin-top: 20px;
    .downLoadtemplate {
      height: 30px;
      width: 100px;
      margin-right: 20px;
      background-color: #deefff;
    }
  }
  .uploader-example {
    margin-top: 10px;

    .select_file {
      background-color: #348efc;
      color: #fff;
      border: none;
      width: 84px;
      height: 22px;
      line-height: 22px;
      text-align: center;
    }
  }
  .zh-import-text {
    font-size: 12px;
    color: #999;
    line-height: 30px;
    margin: 20px;
    p {
      margin: 0;
    }
    span {
      color: #cf537c;
    }
  }
  .zh-import-table {
    p {
      font-size: 16px;
      margin-bottom: 20px;
    }
  }
  .uploader-list {
    .uploader-file-pause {
      display: none !important;
    }
    .uploader-file-status {
      text-indent: 0;
    }
  }

  .el-table__header-wrapper table thead {
    tr:first-child {
      th:nth-child(2),
      th:nth-child(13) {
        color: red;
      }

      th:nth-child(13) {
        border-bottom: inherit;
      }
    }

    tr:last-child {
      th:nth-child(1),
      th:nth-child(2),
      th:nth-child(3),
      th:nth-child(4),
      th:nth-child(5) {
        color: red;
      }
    }
  }
}

.class_course {
  display: flex;
  flex-direction: column;

  .section_info {
    display: flex;
    flex-direction: column;
    align-items: center;

    div {
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 16px;
        height: 16px;
        margin-right: 5px;
      }
    }
  }
}

.class_section {
  display: flex;
  flex-direction: column;
}

.upload_search {
  display: flex;
  padding: 10px;
  box-sizing: border-box;
  width: 100%;
  margin-top: 10px;
  background-color: #f2f2f2;

  .search_box {
    display: flex;
    margin-right: 20px;
    align-items: center;
    span {
      width: 95px;
    }
  }
}

.import_container {
  margin-top: 20px;
  .import_ul {
    .size {
      color: #999;
    }

    .normal {
      color: #000;
    }

    .error {
      color: #c42e5f;
    }
    .success {
      color: #2ec431;
    }

    img {
      width: 16px;
      height: 16px;
      cursor: pointer;
    }

    .error_info {
      cursor: pointer;
      color: #348efc;
      margin-left: 20px;
    }
  }
}

.view_ul {
  padding-bottom: 30px;
}
</style>
